package token

import (
	"github.com/medivhzhan/weapp/token"
	"github.com/sirupsen/logrus"
	"gitee.com/xiaofengfeng123/srv-paper-tape/config"
	"time"
)

var Token *WeToken

func Init(){
	Token = NewWeToken()
}

type WeToken struct {
	Token      string
	timestamp  time.Time
}

func (w *WeToken)Get()string{
	if w.Token == "" || w.Expire(){
		tok, exp, err := token.AccessToken(config.AppID, config.Aecret)
		if err !=nil{
			logrus.Error(err.Error())
			return ""
		}
		w.Token = tok
		w.timestamp = time.Now().Add(exp)
	}
	logrus.Infof("expire: %s,expire time: %d,now: %d",w.Expire(),w.timestamp.UnixNano(),time.Now().UnixNano())
	return w.Token
}

func (w *WeToken)Expire()bool{
	return w.timestamp.UnixNano() < time.Now().UnixNano()
}

func NewWeToken()*WeToken{
	token := new(WeToken)
	token.timestamp = time.Now()
	return token
}
